﻿using CommonLibrary;
using System.IO;
using System.Net;
using System.Text;
using System;

/// <summary>
/// API 协助类
/// </summary>
public class ApiHelper
{
    /// <summary>
    /// 基础验证，用户名密码
    /// </summary>
    /// <param name="username"></param>
    /// <param name="password"></param>
    /// <returns></returns>
    private static string GenEncodeCredentials(string username, string password)
    {
        return Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}"));
    }
    /// <summary>
    /// Http 调用
    /// 成功的话，有数据返回，失败的话返回空字符串
    /// </summary>
    /// <param name="url">url地址</param>
    /// <param name="requestBody">请求内容</param>
    /// <param name="contentType">[application/json,application/x-www-form-urlencoded;charset=UTF-8]</param>
    /// <param name="password"></param>
    /// <param name="username"></param>
    /// <param name="timeout">默认5000毫秒</param>
    /// <returns></returns>
    public static (string result, string exception, bool isTimeout) 
        Post(string url, string requestBody, 
        string username = "", string password = "", 
        string contentType = "application/x-www-form-urlencoded;charset=UTF-8", int timeout = 5000)
    {
        LogHelper.Info($"【请求开始】 地址:{url}, 请求数据: {requestBody}");
        string result = string.Empty;
        string exception = string.Empty;
        bool isTimeout = false;
        if (!string.IsNullOrWhiteSpace(url))
        {
            if (url.ToLower().StartsWith("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
            }

            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = contentType;
            request.Accept = "application/json,text/xml,text/javascript";
            if (!string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(password))
            {
                request.Headers.Add("Authorization", $"Basic {GenEncodeCredentials(username, password)}");
            }
            request.Timeout = timeout;

            StreamReader reader = null;

            try
            {
                byte[] buffer = encoding.GetBytes(requestBody);
                request.ContentLength = buffer.Length;
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(buffer, 0, buffer.Length);
                    stream.Close();
                    stream.Dispose();
                }
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                using (reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                if (ex is WebException && ((WebException)ex).Status == WebExceptionStatus.Timeout)
                {
                    isTimeout = true;
                }
                LogHelper.Error(ex, "", url);
                exception = ex.Message;
                result = string.Empty;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                    reader.Dispose();
                    reader = null;
                }
            }
        }
        LogHelper.Info($"【Post 结束】 结果: {result}【{exception}】，地址:{url}，请求数据: {requestBody}");
        return (result, exception, isTimeout);
    }
}